import { Card } from 'antd'
import logo from '../../assets/logo.png'
import styles from './index.module.scss'
import { Form, Input, Button, Checkbox, message } from 'antd'
import { useDispatch } from 'react-redux'
import { login } from '@/store/actions/login'
import { useHistory, useLocation } from 'react-router-dom'
import { useState } from 'react'

const Login = () => {
  console.log(styles)
  const dispatch = useDispatch()
  const history = useHistory()
  const location = useLocation()
  // console.log(location)

  const [isLoading, setIsLoading] = useState(false)

  const onFinish = async (values) => {
    // console.log(values)
    try {
      setIsLoading(true)
      await dispatch(login(values))
      message.success('登录成功', 1, () => {
        // history.push('/home')
        const path = location?.state?.from || '/home'
        history.replace(path)
      })
    } catch (e) {
      setIsLoading(false)
      message.error(e.response.data.message)
    }
  }
  return (
    <div className={styles.login}>
      <Card className="login-container">
        {/* 图片 */}
        <img className="login-logo" src={logo} alt="" />
        {/* 登录表单 */}
        <Form
          autoComplete="off"
          onFinish={onFinish}
          initialValues={{
            mobile: '13911111111',
            code: '246810',
            agree: true,
          }}
        >
          <Form.Item
            validateTrigger={['onBlur', 'onChange']}
            name="mobile"
            rules={[
              { required: true, message: '请输入手机号' },
              {
                pattern: /^1[3-9]\d{9}$/,
                message: '手机号码格式不对',
              },
            ]}
          >
            <Input placeholder="请输入手机号" />
          </Form.Item>

          <Form.Item
            name="code"
            rules={[
              { required: true, message: '请输入验证码' },
              { len: 6, message: '请输入6位验证码' },
            ]}
          >
            <Input placeholder="请输入验证码" />
          </Form.Item>

          <Form.Item
            name="agree"
            valuePropName="checked"
            rules={[
              {
                validator: (_, value) => {
                  if (value === true) {
                    return Promise.resolve()
                  } else {
                    return Promise.reject(new Error('请阅读并同意条款和协议'))
                  }
                },
              },
            ]}
          >
            <Checkbox>我已阅读并同意[隐私条款]和[用户协议]</Checkbox>
          </Form.Item>

          <Form.Item>
            <Button
              loading={isLoading}
              type="primary"
              htmlType="submit"
              size="large"
              block
            >
              登录
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}

export default Login
